<?php

declare(strict_types=1);

namespace Creatcode\Crontask\command;

use Creatcode\Crontask\HttpCrontab;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class TaskCommand extends Command
{
    protected static $config = [
        // 进程名称
        'name' => '',
        //监听地址和端口
        'base_url' => '',
        //任务锁驱动 mysql，redis,不设置表示不开启
        'driver' => '',
        //安全秘钥，设置安全密钥需要在请求头或者参数附带key，
        'safe_key' => '',
        // 开启任务日志
        'log' => false
    ];

    public static function getconfig()
    {
        $extraConfig = config('crontabtask');
        if (!$extraConfig) {
            $extraConfig = config('crontabtask.');
        }
        return array_merge(self::$config, $extraConfig ?? []);
    }

    /**
     * 指令配置
     */
    protected function configure()
    {
        $this->setName('crontask')
            ->addArgument('action', Argument::OPTIONAL, 'start|stop|restart|reload|status|connections', 'start')
            ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the http crontab server in daemon mode.')
            ->addOption('debug', null, Option::VALUE_NONE, 'Print log')
            ->setDescription('Run http crontab server');
    }

    /**
     * 执行指令
     *
     * @param Input $input
     * @param Output $output
     */
    protected function execute(Input $input, Output $output)
    {
        $action = trim($input->getArgument('action'));
        if (!in_array($action, ['start', 'stop', 'restart', 'reload', 'status', 'connections'])) {
            $this->output->writeln('action参数值非法');
            return false;
        }
        $options = $input->getOptions();
        $taskConfig = $this->getconfig();
        if (!$taskConfig['base_url']) {
            $this->output->writeln('base_url不能为空');
            return false;
        }

        // 获取配置
        $all_config = config();
        $version = defined('\think\App::VERSION') ? \think\App::VERSION : '5.0';
        $isTp6 = version_compare($version, '6.0', '>=');

        if (strtolower($taskConfig['driver']) == 'redis') {
            $cacheConfig = $isTp6 ? $all_config['cache']['stores'] : $all_config['cache'];
            if (!isset($cacheConfig['redis'])) {
                $this->output->writeln('请先配置redis缓存');
                return false;
            }
        }

        $url = "tcp://" . $taskConfig['base_url'];
        $server   = new HttpCrontab($url);

        $dataBaseConfig = $all_config['database'];
        if ($isTp6) {
            $dataBaseConfig = $dataBaseConfig['connections'][$dataBaseConfig['default']];
        }

        $server->setName($taskConfig['name'] ?: 'Crontask Server')
            ->setDbConfig($dataBaseConfig ?? [])
            ->setLog($taskConfig['log'])
            ->setLock($taskConfig['driver']);

        if ($taskConfig['safe_key'] !== null && $taskConfig['safe_key']) {
            $server->setSafeKey($taskConfig['safe_key']);
        }

        $options['debug'] && $server->setDebug();
        $server->run();
    }
}
